package com.example.storage;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder> {
    private List<Fooditem> foodList;

    public class ViewHolder extends RecyclerView.ViewHolder {
        // ViewHolder 内部类的实现
        View foodView;
        TextView FoodName;
        ImageView Img;
        TextView Calories;
        TextView Unit;

        public ViewHolder(View itemView) {
            super(itemView);
            // 初始化 ViewHolder 中的视图  来自fooditem.xml
            foodView = itemView;
            FoodName = (TextView) itemView.findViewById(R.id.text_foodname);
            Img=(ImageView) itemView.findViewById(R.id.foodimageView);
            Calories = (TextView) itemView.findViewById(R.id.text_calories);
            //Unit = (TextView) itemView.findViewById(R.id.text_unit);
        }
    }

    public FoodAdapter(List<Fooditem> foodList) {
        this.foodList = foodList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_fooditem, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        holder.foodView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fooditem fooditem = foodList.get(position);

                // 创建一个 Intent
                Intent resultIntent = new Intent();
                // 将 Fooditem 对象添加到 Intent 中作为附加数据
                resultIntent.putExtra("food_item", fooditem);
                // 设置结果码和结果数据
                ((Activity) v.getContext()).setResult(Activity.RESULT_OK, resultIntent);
                // 结束当前的活动
                ((Activity) v.getContext()).finish();

            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fooditem fooditem = foodList.get(position);
        // 在这里绑定数据到 ViewHolder 对象
        holder.FoodName.setText(fooditem.getFoodname());
        Glide.with(holder.Img.getContext()) // 使用Glide加载图片
                .load(fooditem.getImg())
                .apply(RequestOptions.bitmapTransform(new CircleCrop())) // 使用 CircleCrop 将图片裁剪成圆形
                .into(holder.Img); // 将下载的图片放入ImageView
        holder.Calories.setText(fooditem.getCalories()+"大卡/"+fooditem.getUnit()+"克");
    }

    @Override
    public int getItemCount() {
        return foodList.size();
    }

}
